package de.fmannan.addbook.editor;

import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionDelegate;

import de.fmannan.addbook.domainmodel.Contact;
import de.fmannan.addbook.domainmodel.Group;


public class OpenEditorActionDelegate extends ActionDelegate {

	private static Logger log = Logger.getLogger(OpenEditorActionDelegate.class);
	
	
	public static void openEditor(IWorkbenchPage page, ISelection selection) 
	{
		Object elem = ((IStructuredSelection)selection).getFirstElement();
		//Do nothing if object can not be adapted
		if (!(elem instanceof IAdaptable))
			return;
		
		openEditor(page, (IAdaptable)elem);
	}
	
	/**
	 * Delegates the adaptable object to the {@link GenericEditor} in order to
	 * display its fields.
	 * 
	 * @param page
	 * @param elem
	 */
	public static void openEditor (IWorkbenchPage page, IAdaptable elem) {
		// Open an editor which reflects the field of this adaptable Item
		try {
			if(elem instanceof Group) {
				log.debug("Trying to open Group Editor window...");
				page.openEditor((IEditorInput) new GroupEditorInputAdapter((Group)elem, Group.class), "de.fmannan.addbook.editor.GenericEditor");				
			} else if(elem instanceof Contact) {
				log.debug("Trying to open Contact Editor window...");
				page.openEditor((IEditorInput) new ContactEditorInputAdapter((Contact)elem, Contact.class), "de.fmannan.addbook.editor.GenericEditor");				
			}
			
		} catch (PartInitException e) {
			log.error("Opening the editor failed.");
		}		
	}
}
